import { app, shell, BrowserWindow, ipcMain } from 'electron';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import { getAppName } from './utils';
import { setTopBrowserWindow } from './ipc';
import { cache } from './store';
const IS_DEBUG = process.env.NODE_ENV == 'development';
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
    app.quit()
}

let mainWindow: BrowserWindow;
cache.set('__is_main__', false);

ipcMain.on('__restart__', () => {
  const oldWin = mainWindow;
  createWindow();
  oldWin.close();

});

function createWindow(): void {
  const isMain = cache.get('__is_main__');
  let width = 1350;
  let height = 850;

  if (!isMain) {
    width = 380;
    height = 330;
  }
  mainWindow = new BrowserWindow({
    width,
    height,
    title: getAppName(),
    show: false,
    maximizable: IS_DEBUG,
    resizable: IS_DEBUG,
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true,
      webviewTag: true,
      webSecurity: false,
    }
  })
  mainWindow.setMenu(null);
  setTopBrowserWindow(mainWindow);

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.webContents.openDevTools();
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
